package com.gc.tpas.controller;

import com.gc.tpas.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Created by Administrator on 2018/5/7.
 */
@Controller
public class UploadController {
    @Value("${imgdir}")
    String imgdir;
    @RequestMapping("/uploadimg")
    @ResponseBody
    public Result upload(MultipartFile myfile, HttpServletRequest request){
        Result result = new Result();
        if(myfile==null || myfile.isEmpty()){
            result.setErrno(1);
        }else{
            try {
                String filename = UUID.randomUUID()+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
                String basepath = request.getServletContext().getRealPath("");
                String savepath = imgdir+filename;
                File savefile = new File(basepath+savepath);
                myfile.transferTo(savefile);
                result.setData(new String[]{savepath});
            } catch (Exception e) {
                e.printStackTrace();
                result.setErrno(2);
            }
        }
        return result;
    }
}
